import React, { useState } from 'react'
import { Card, Input, Select, List, AutoComplete, Tag } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import './style.less'

const { Option } = Select

const allArticles = [
  {
    id: 1,
    title: 'AI时代的来临，不懂AI的我们，怎么不被时代抛弃？',
    author: '第七梅雨',
    date: '2025-06-23',
    tags: ['AI', '工作'],
    summary: '处于 AI 时代洪流的我们，能够做些什么呢？',
    link: 'https://mp.weixin.qq.com/s/b4QFcrPiNNTyrC4ysx-1nQ',
  },
  {
    id: 2,
    title: '自然语言处理的发展史',
    author: '康康',
    date: '2025-06-11',
    tags: ['NLP', '自然语言处理', 'AI'],
    summary: '自然语言处理的发展',
    link: 'https://mp.weixin.qq.com/s/VeSKCfSgdBcamzNjLjfJfw',
  },
  {
    id: 3,
    title: 'Gemini 免费申请教程',
    author: '杨逸洋',
    date: '2025-06-10',
    tags: ['人工智能', '谷歌'],
    summary: '什么是Gemini',
    link: 'https://mp.weixin.qq.com/s/4VbqU_F6Jj0iGj9KemNyUg',
  },
  {
    id: 4,
    title: '前端精选系列（十）:《ECharts ：不强不大，做点可视化》',
    author: '贺越',
    date: '2025-05-16',
    tags: ['前端', 'ECharts'],
    summary: 'ECharts 是一个强大的数据可视化库，广泛应用于前端开发中',
    link: 'https://mp.weixin.qq.com/s/CW8YuAGqr1ydf5swCOdRlQ',
  },
  {
    id: 5,
    title: 'Llama:开源的急先锋',
    author: '康康',
    date: '2025-05-15',
    tags: ['AI', '模型'],
    summary: 'Llama1:开放、高效的基础语言模型',
    link: 'https://mp.weixin.qq.com/s/C6MBqJ2eb6NrGQTgvkxc5A',
  },
  {
    id: 6,
    title: 'MySQL可重复读:幻读真的被攻克了吗',
    author: '后端',
    date: '2025-04-29',
    tags: ['后端', '数据库'],
    summary:
      'MySQL InnoDB引擎的默认隔离级别是可重复读,它很大程度上避免了幻读现象,避免方案有两种',
    link: 'https://mp.weixin.qq.com/s/cN9e-21fA5zV9rdb0MbitQ',
  },
]

// 转义正则特殊字符
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

// React 版高亮渲染（用 span 避免默认斜体）
const renderSuggest = (text, keyword) => {
  if (!keyword) return text
  const kw = keyword.trim()
  if (!kw) return text

  let suggestHighlight = text
  try {
    suggestHighlight = suggestHighlight.replace(
      new RegExp(`(${escapeRegExp(kw)})`, 'gi'),
      `<span class="highlight-tag">$1</span>`
    )
  } catch (e) {
    console.log('suggest error', e)
  }

  return (
    <span dangerouslySetInnerHTML={{ __html: suggestHighlight }} />
  )
}

export default function ArticlesPage() {
  const [searchValue, setSearchValue] = useState('')
  const [filteredArticles, setFilteredArticles] = useState(allArticles)
  const [selectedCategory, setSelectedCategory] = useState('全部分类')
  const [options, setOptions] = useState([])

  const applyFilters = (keyword, category) => {
    let list = allArticles
    const kw = (keyword || '').trim().toLowerCase()

    if (kw) {
      list = list.filter(
        (a) =>
          a.title.toLowerCase().includes(kw) ||
          a.author.toLowerCase().includes(kw) ||
          a.tags.some((t) => t.toLowerCase().includes(kw)) ||
          a.summary.toLowerCase().includes(kw)
      )
    }

    if (category && category !== '全部分类') {
      list = list.filter((a) => a.tags.includes(category))
    }

    setFilteredArticles(list)
  }

  const handleSearch = (value) => {
    setSearchValue(value)
    const val = (value || '').trim()
    if (!val) {
      setOptions([])
      applyFilters('', selectedCategory)
      return
    }

    const kw = val.toLowerCase()
    const matched = allArticles.filter(
      (a) =>
        a.title.toLowerCase().includes(kw) ||
        a.author.toLowerCase().includes(kw) ||
        a.tags.some((t) => t.toLowerCase().includes(kw)) ||
        a.summary.toLowerCase().includes(kw)
    )

    setOptions(
      matched.map((a) => ({
        value: a.title,
        label: (
          <div className="autocomplete-item">
            <div className="autocomplete-title">
              {renderSuggest(a.title, val)}
            </div>
            <small className="autocomplete-author">
              作者: {renderSuggest(a.author, val)}
            </small>
          </div>
        ),
      }))
    )

    applyFilters(val, selectedCategory)
  }

  const handleSelect = (value) => {
    setSearchValue(value)
    applyFilters(value, selectedCategory)
    setOptions([]) // 收起下拉
  }

  const handleCategoryChange = (category) => {
    setSelectedCategory(category)
    applyFilters(searchValue, category)
  }

  return (
    <div className="articles-container">
      <div className="articles-intro">
        <h1>文章列表</h1>
        <p>通过搜索标题或作者名可在下拉里看到高亮（标题 & 作者）。</p>
      </div>

      <div className="articles-filter">
        <AutoComplete
          options={options}
          value={searchValue}
          onSearch={handleSearch}
          onChange={handleSearch}
          onSelect={handleSelect}
          filterOption={false}
          style={{ width: '60%', marginRight: 16 }}
        >
          <Input
            size="large"
            placeholder="搜索文章标题、作者或标签"
            prefix={<SearchOutlined />}
            allowClear
          />
        </AutoComplete>

        <Select
          value={selectedCategory}
          style={{ width: '30%' }}
          onChange={handleCategoryChange}
        >
          <Option value="全部分类">全部分类</Option>
          <Option value="AI">AI</Option>
          <Option value="科技">科技</Option>
          <Option value="前端">前端</Option>
          <Option value="React">React</Option>
          <Option value="Vue">Vue</Option>
          <Option value="JavaScript">JavaScript</Option>
          <Option value="区块链">区块链</Option>
          <Option value="金融">金融</Option>
          <Option value="量子计算">量子计算</Option>
        </Select>
      </div>

      <List
        grid={{ gutter: 16, column: 2 }}
        dataSource={filteredArticles}
        pagination={{ pageSize: 4, showSizeChanger: false }}
        renderItem={(article) => (
          <List.Item>
            <Card title={renderSuggest(article.title, searchValue)} bordered>
              <p>
                作者: {renderSuggest(article.author, searchValue)} | 日期: {article.date}
              </p>

              <div className="article-tags">
                {article.tags.map((tag) => (
                  <Tag key={tag} color="blue">
                    {tag}
                  </Tag>
                ))}
              </div>

              <p className="article-summary">
                {renderSuggest(article.summary, searchValue)}
              </p>

              <div className="article-footer">
                <a href={article.link} target="_blank" rel="noreferrer">
                  阅读全文
                </a>
              </div>
            </Card>
          </List.Item>
        )}
      />
    </div>
  )
}
